<template>
  <div>
    <custom-dialog v-model:visible="dialogVisible" top="2vh" curent-class="food-package-dialog">
      <div class="content-box" v-if="selectedCurrentFoodGroup">
        <div class="title-box">
          <div class="name-box">
            <div class="name">{{ selectedCurrentFoodGroup.foodGroupName }}</div>
            <div class="money">{{ selectedCurrentFoodGroup.price }}元</div>
          </div>
          <div class="btn-box">
            <div
              class="btn-item"
              :class="{ 'btn-item-active': selectActiveIndex === index }"
              v-for="(item, index) in foodGroupButtonList"
              :key="item.name + index"
              @click="handleSelectButton(index, item)"
            >
              {{ item.name }}
            </div>
          </div>
        </div>
        <div class="food-list-box" v-loading="loading">
          <div class="scroll-left-box">
            <div class="scroll-left-title">套餐已选菜品</div>
            <div class="scroll-left-item" v-for="item in foodGroupSelectFoodList" :key="item.id">
              <div class="sold-out" v-if="item.bind_num != -1 && item.num > item.bind_num">
                <img class="image" src="@/assets/images/home/yishouqing-icon.png" alt="" />
              </div>
              <img class="image" :src="item.sku.foodInfo.images[0].file.preview_url" alt="" />
              <div class="desc-box">
                <div class="title">{{ item.sku.foodInfo.name || '' }}</div>
                <div class="money">￥{{ item.sku.price }}/{{ item.sku.unit }}</div>
                <div class="element-input-box">
                  <el-input-number
                    v-if="item.bind_num != -1 && item.num > item.bind_num"
                    class="element-input-inner"
                    v-model="soldOutNum"
                    step-strictly
                    :min="0"
                    disabled
                  ></el-input-number>
                  <el-input-number
                    v-else
                    class="element-input-inner"
                    v-model="item.num"
                    step-strictly
                    :min="0"
                    disabled
                    @change="handleFoodNumberChange($event, item)"
                  ></el-input-number>
                </div>
              </div>
            </div>
          </div>
          <div class="scroll-right-box">
            <template v-if="foodGrouplList.length">
              <div
                class="scroll-right-item"
                v-for="item in foodGrouplList"
                :key="item.id"
                @click="handleSelectFood(item)"
              >
                <div class="sold-out" v-if="item.bind_num != -1 && item.num > item.bind_num">
                  <img class="image" src="@/assets/images/home/yishouqing-icon.png" alt="" />
                </div>

                <img class="image" :src="item.sku.foodInfo.images[0].file.preview_url" alt="" />
                <div class="desc-box">
                  <div class="title">{{ item.sku.foodInfo.name || '' }}</div>
                  <div class="money">￥{{ item.sku.price }}/{{ item.sku.unit }}</div>
                </div>
                <!-- 显示选中菜品的图标 -->
                <img
                  v-if="item.isChecked"
                  class="choose-img"
                  src="@/assets/images/home/xuanzhongzhuotai.png"
                  alt=""
                />
              </div>
            </template>
            <div v-else class="no-data-container">
              <NotData desc="暂无可选菜品" />
            </div>
          </div>
        </div>
        <div class="btn-box">
          <div class="cancel-btn" @click="onCancel">取消</div>
          <div class="confirm-btn" @click="onConfirm">确定</div>
        </div>
      </div>
    </custom-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import CustomDialog from '@/components/CustomDialog/Index.vue'
import NotData from '@/components/NotData/Index.vue'
import { foodGroupDetail } from '@/api/food'

interface Props {
  visible: boolean
  currentGroupFoodId: string
  selectedCurrentFoodGroup: any
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'confirm', data: any): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 控制弹窗显示
const dialogVisible = computed({
  get: () => props.visible,
  set: val => emit('update:visible', val)
})

// 选中的索引
const selectActiveIndex = ref(-1)
// 套餐下面的菜品列表
const foodGrouplList = ref<any[]>([])
// 已经选中的菜品列表（总的）
const selectActiveAllFoodList = ref<any[]>([])
// 当前套餐可以选择菜品的数量
const selectedFoodNum = ref(0)
// 已经选中的菜品列表（针对当前索引）
const selectActiveCurrentFoodList = ref<any[]>([])
// 判断是否已经全部选中可选的菜品
const selectChooseFoodList = ref<any[]>([])
// 渲染套餐已选的菜品列表
const foodGroupSelectFoodList = ref<any[]>([])
const currentFoodGroupDetailList = ref<any[]>([])
// 售罄后显示为0
const soldOutNum = ref(0)
// 加载状态
const loading = ref(false)

// 渲染套餐按钮
const foodGroupButtonList = computed(() => {
  if (currentFoodGroupDetailList.value) {
    return currentFoodGroupDetailList.value.filter((item: any) => item.id !== 0)
  }
  return []
})

// 监听弹窗显示状态
watch(dialogVisible, val => {
  if (val) {
    // 先清空之前的数据
    resetFormData()
    // 然后加载新的套餐详情
    loadFoodGroupDetail()
  }
})

// 加载套餐详情
const loadFoodGroupDetail = async () => {
  try {
    loading.value = true
    const res = await foodGroupDetail({ foodgroup_id: props.currentGroupFoodId })
    if (res?.status === 200) {
      currentFoodGroupDetailList.value = res.data

      // 默认选中的固定菜品
      let defaultFoodList: any[] = []
      currentFoodGroupDetailList.value.forEach((item: any) => {
        if (item.id === 0) {
          defaultFoodList = item.foodList
        }
      })
      foodGroupSelectFoodList.value = defaultFoodList

      // 默认选中第一个分类
      const buttonList = currentFoodGroupDetailList.value.filter((item: any) => item.id !== 0)
      if (buttonList.length > 0) {
        // 对所有分类进行自动勾选检查（如果选项数量等于需要选择的数量，自动全部勾选）
        buttonList.forEach((datas: any, index: number) => {
          const foodList = datas.foodList || []
          // 过滤掉已售罄的菜品
          const availableFoods = foodList.filter(
            (item: any) => !(item.bind_num != -1 && item.num > item.bind_num)
          )
          // 如果可选菜品数量正好等于需要选择的数量，自动全部勾选
          if (availableFoods.length === datas.selected_num && availableFoods.length > 0) {
            // 检查是否已经选中（避免重复添加）
            availableFoods.forEach((item: any) => {
              const exists = selectActiveAllFoodList.value.find((selected: any) => selected.id === item.id)
              if (!exists) {
                item.foodTaoCanId = datas.id
                item.isChecked = true
                selectActiveAllFoodList.value.push(item)
                selectChooseFoodList.value.push(item.foodTaoCanId)
                // 添加到左侧已选菜品列表
                foodGroupSelectFoodList.value.push(item)
              }
            })
          }
        })
        
        // 处理第一个分类的显示（会自动回显已勾选的菜品）
        handleSelectButton(0, buttonList[0])
      }
    }
  } catch (error) {
    console.error('加载套餐详情失败:', error)
    ElMessage.error('加载套餐详情失败')
  } finally {
    loading.value = false
  }
}

// 选中当前的索引，获取当前套餐下面的菜品列表
const handleSelectButton = (index: number, datas: any) => {
  selectActiveIndex.value = index
  // 重置
  foodGroupButtonList.value[index].foodList.forEach((item: any) => {
    item.isChecked = false
    // 只做当前页面提交的相关判断专用，无其他作用
    item.foodTaoCanId = datas.id
  })
  selectActiveCurrentFoodList.value = []
  foodGrouplList.value = foodGroupButtonList.value[index].foodList
  selectedFoodNum.value = datas.selected_num

  // 回显已经选中的菜品
  selectActiveAllFoodList.value.forEach((item: any) => {
    foodGrouplList.value.forEach((itm: any) => {
      if (itm.id === item.id) {
        item.isChecked = true
        selectActiveCurrentFoodList.value.push(item)
      }
    })
  })

  // 如果可选菜品数量等于需要选择的数量，且没有已选中的，自动全部勾选
  if (selectActiveCurrentFoodList.value.length === 0) {
    // 过滤掉已售罄的菜品
    const availableFoods = foodGrouplList.value.filter(
      (item: any) => !(item.bind_num != -1 && item.num > item.bind_num)
    )
    // 如果可选菜品数量正好等于需要选择的数量，自动全部勾选
    if (availableFoods.length === selectedFoodNum.value && availableFoods.length > 0) {
      availableFoods.forEach((item: any) => {
        item.isChecked = true
        selectActiveAllFoodList.value.push(item)
        selectActiveCurrentFoodList.value.push(item)
        selectChooseFoodList.value.push(item.foodTaoCanId)
        // 添加到左侧已选菜品列表
        foodGroupSelectFoodList.value.push(item)
      })
    }
  }
}

// 选中对应的菜品
const handleSelectFood = (item: any) => {
  if (item.bind_num != -1 && item.num > item.bind_num) {
    return ElMessage.warning('当前菜品已售罄')
  }

  const activeIndex = selectActiveAllFoodList.value.findIndex((itm: any) => itm.id === item.id)
  if (activeIndex === -1) {
    if (selectActiveCurrentFoodList.value.length >= selectedFoodNum.value) {
      ElMessage.warning(`当前套餐最多只能选择${selectedFoodNum.value}个菜品哦~`)
      return
    }
    item.isChecked = true
    selectActiveAllFoodList.value.push(item)
    selectActiveCurrentFoodList.value.push(item)
    selectChooseFoodList.value.push(item.foodTaoCanId)
    // 添加到左侧已选菜品列表
    foodGroupSelectFoodList.value.push(item)
  } else {
    item.isChecked = false
    selectActiveAllFoodList.value = selectActiveAllFoodList.value.filter(
      (allFood: any) => allFood.id !== item.id
    )
    selectActiveCurrentFoodList.value = selectActiveCurrentFoodList.value.filter(
      (curFood: any) => curFood.id !== item.id
    )
    selectChooseFoodList.value = selectChooseFoodList.value.filter(
      (curFood: any) => curFood !== item.foodTaoCanId
    )
    // 从左侧已选菜品列表中移除
    foodGroupSelectFoodList.value = foodGroupSelectFoodList.value.filter(
      (selectedFood: any) => selectedFood.id !== item.id
    )
  }
}

// 取消事件
const onCancel = () => {
  dialogVisible.value = false
  resetFormData()
}

// 确定事件
const onConfirm = () => {
  // 验证是否选择了菜品
  if (!foodGroupSelectFoodList.value || foodGroupSelectFoodList.value.length === 0) {
    ElMessage.warning('请至少选择一个菜品')
    return
  }

  // 做数组去重
  selectChooseFoodList.value = Array.from(new Set(selectChooseFoodList.value))

  const foodIdsList = foodGroupSelectFoodList.value.map((item: any) => {
    return {
      food_sku_id: item.food_sku_id,
      num: item.bind_num != -1 && item.num > item.bind_num ? 0 : item.num
    }
  })

  const foodData = {
    food_sku_id: props.selectedCurrentFoodGroup.food_sku_id, // 菜品详情id
    foodNum: 1, // 套餐数量
    discount: 10, // 套餐折扣，折扣范围1-10 ， 10为不打折
    // 判断是否使用了单菜折扣
    isUseSingleFoodDiscount: false,
    food_ids: foodIdsList, // 套餐选择的菜品id数组集合
    is_group: 1, // 1是套餐，0不是套餐
    foodgroup_id: props.selectedCurrentFoodGroup.foodGroupId, // 套餐id
    foodGroupName: props.selectedCurrentFoodGroup.foodGroupName, // 套餐名称
    foodPrice: props.selectedCurrentFoodGroup.price, // 菜品原价
    foodUnit: props.selectedCurrentFoodGroup.foodUnit, // 菜品单位
    foodTotalPrice: props.selectedCurrentFoodGroup.price, // 菜品总价
    foodGroupSelectFoodList: foodGroupSelectFoodList.value, // 页面展示使用，不提交给后端
    ...props.selectedCurrentFoodGroup
  }

  emit('confirm', foodData)
  dialogVisible.value = false
  resetFormData()
}

// 重置数据
const resetFormData = () => {
  // 选中的索引
  selectActiveIndex.value = -1
  // 套餐下面的菜品列表
  foodGrouplList.value = []
  // 已经选中的菜品列表（总的）
  selectActiveAllFoodList.value = []
  // 当前套餐可以选择菜品的数量
  selectedFoodNum.value = 0
  // 已经选中的菜品列表（针对当前索引）
  selectActiveCurrentFoodList.value = []
  // 判断是否已经全部选中可选的菜品
  selectChooseFoodList.value = []
  // 渲染套餐已选的菜品列表
  foodGroupSelectFoodList.value = []
  // 当前套餐详情列表
  currentFoodGroupDetailList.value = []
}

// 切换当前套餐里面的菜品的数量，减是退菜，增是加菜
const handleFoodNumberChange = (num: number, food: any, foodGroup?: any) => {
  // 过滤数量不为0的
  selectActiveAllFoodList.value = selectActiveAllFoodList.value.filter((i: any) => i.num !== 0)
  foodGroupSelectFoodList.value = foodGroupSelectFoodList.value.filter((i: any) => i.num !== 0)
}
</script>

<style scoped lang="scss">
.content-box {
  min-width: 1090px;

  .title-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .name-box {
      display: flex;
      align-items: center;
      font-size: 20px;
      font-family:
        PingFang SC,
        PingFang SC-Bold;
      font-weight: 700;
      color: #333333;
      .name {
        margin-right: 20px;
      }
    }
    .btn-box {
      display: flex;
      align-items: center;
      .btn-item {
        display: inline-block;
        padding: 0 30px;
        height: 52px;
        line-height: 52px;
        background: #ffffff;
        border: 1px solid #707070;
        border-radius: 12px;
        font-size: 18px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: center;
        color: #333333;
        margin-right: 30px;
        cursor: pointer;
      }
      .btn-item-active {
        border: 1px solid #7c0a03;
        color: #7c0a03;
      }
    }
  }
  .food-list-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 20px;
    .scroll-left-box {
      width: 427px;
      height: 587px;
      box-sizing: border-box;
      overflow-y: auto;
      background: #ffffff;
      border: 1px solid #d2d2d2;
      border-radius: 12px;
      .scroll-left-title {
        font-size: 16px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: left;
        color: #333333;
        padding: 26px 0 10px 20px;
      }
      .scroll-left-item {
        position: relative;
        display: flex;
        align-items: center;
        padding: 20px 30px;
        border-bottom: 1px solid #e2e2e2;
        .sold-out {
          position: absolute;
          top: 20px;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 173px;
          height: 130px;
          background-color: rgba(0, 0, 0, 0.5);
          border-radius: 12px;
          img {
            width: 70%;
            height: 70%;
            border-radius: 12px;
          }
        }
        .image {
          width: 173px;
          height: 130px;
          border-radius: 12px;
          margin-right: 12px;
        }
        .desc-box {
          .title {
            font-size: 18px;
            font-family:
              PingFang SC,
              PingFang SC-Bold;
            font-weight: 700;
            text-align: left;
            color: #333333;
          }
          .money {
            font-size: 14px;
            font-family:
              PingFang SC,
              PingFang SC-Bold;
            font-weight: 700;
            text-align: left;
            color: #333333;
            margin-top: 12px;
          }
          .element-input-box {
            margin-top: 20px;
            .element-input-inner {
              width: 180px;
            }
          }
        }
      }
      .scroll-left-item:last-child {
        border-bottom: none;
      }
    }
    //滚动条整体的大小
    .scroll-left-box::-webkit-scrollbar {
      width: 6px !important;
      height: 0 !important;
    }
    //滚动条里滑动的滑块
    .scroll-left-box::-webkit-scrollbar-thumb {
      height: 100px !important;
      background: #d2d2d2 !important;
      border-radius: 3px !important;
    }
    //滚动条底层样式
    .scroll-left-box::-webkit-scrollbar-track {
      display: none !important;
    }

    .scroll-right-box {
      width: 499px;
      height: 581px;
      overflow-y: auto;
      background: #f4f4f4;
      border-radius: 12px;
      box-sizing: border-box;
      padding: 30px;
      .scroll-right-item {
        position: relative;
        display: flex;
        align-items: center;
        width: 100%;
        height: 130px;
        box-sizing: border-box;
        background: #ffffff;
        border-radius: 12px;
        margin-bottom: 20px;
        cursor: pointer;
        .sold-out {
          position: absolute;
          top: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 173px;
          height: 130px;
          background-color: rgba(0, 0, 0, 0.5);
          border-radius: 12px;
          img {
            width: 70%;
            height: 70%;
            border-radius: 12px;
          }
        }
        .image {
          width: 173px;
          height: 130px;
          border-radius: 12px 0 0 12px;
          margin-right: 12px;
        }
        .desc-box {
          .title {
            font-size: 18px;
            font-family:
              PingFang SC,
              PingFang SC-Bold;
            font-weight: 700;
            text-align: left;
            color: #30314a;
          }
          .money {
            margin-top: 10px;
            font-size: 14px;
            font-family:
              PingFang SC,
              PingFang SC-Bold;
            font-weight: 700;
            text-align: left;
            color: #333333;
          }
        }
        .choose-img {
          position: absolute;
          right: 12px;
          bottom: 12px;
          width: 24px;
          height: 24px;
        }
      }
    }
    //滚动条整体的大小
    .scroll-right-box::-webkit-scrollbar {
      width: 6px !important;
      height: 0 !important;
    }
    //滚动条里滑动的滑块
    .scroll-right-box::-webkit-scrollbar-thumb {
      height: 100px !important;
      background: #d2d2d2 !important;
      border-radius: 3px !important;
    }
    //滚动条底层样式
    .scroll-right-box::-webkit-scrollbar-track {
      display: none !important;
    }

    .no-data-container {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
      min-height: 200px;
    }
  }
  .btn-box {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    height: 60px;
    margin-top: 30px;
    .cancel-btn {
      width: 190px;
      height: 60px;
      background: #ffffff;
      border: 1px solid #333333;
      border-radius: 12px;
      font-size: 18px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      text-align: center;
      color: #333333;
      line-height: 60px;
      cursor: pointer;
      margin-right: 30px;
    }
    .confirm-btn {
      width: 190px;
      height: 60px;
      background: #7c0a03;
      border-radius: 12px;
      font-size: 18px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      text-align: center;
      color: #ffffff;
      line-height: 60px;
      cursor: pointer;
    }
  }
}
</style>
<style lang="scss">
.food-package-dialog {
  max-height: unset !important;
}
</style>
